import {
  createRouter,
  createWebHistory
} from "vue-router";

const routes = [
  {
    path: "/",
    component: () => import("../Home.vue")
  },
  {
    path: "/map/:lon/:lat",
    component: () => import("../Map.vue")
  },
  {
    path: "/login",
    component: () => import("../Login.vue")
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  // 根据token判断是否登录 并且判断token是否过期
  if (localStorage["userToken"] === "fake-token") {
      // 登录了就不允许回到login页面
      if (to.path == '/login') {
      // 返回到login页面就会强制跳转到首页
          next({ path: '/' })
      } else {
      // 没有强制跳转到login页面就放行
          next()
      }
  } else {
      // 未登录
      // 判断路径
      if (to.path == '/login') {
          // 如果本来就在login页面就放行
          next()
      } else {
          // 如果不在login页面就放行到login页面
          next({ path: '/login', query: { redirect: to.path } })
      }
  }

});

export default router;
